#!/bin/bash

#####################################################################
# 快速部署脚本
# 功能：一键部署应用到已配置好的服务器
#####################################################################

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 配置
APP_NAME="kaizeli-app"
APP_JAR="website-0.0.1-SNAPSHOT.jar"
APP_DIR="/opt/kaizeli"
LOG_DIR="$APP_DIR/logs"
CONFIG_FILE="$APP_DIR/application-prod.yml"
JAVA_HOME="/usr/local/java/jdk-21"

# 打印函数
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# 显示标题
show_header() {
    clear
    cat <<EOF
${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}
${GREEN}  Kaizeli项目管理系统 - 快速部署${NC}
${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}

EOF
}

# 检查环境
check_environment() {
    print_info "检查部署环境..."
    
    # 检查Java
    if [ ! -f "$JAVA_HOME/bin/java" ]; then
        print_error "未找到JDK 21: $JAVA_HOME"
        print_info "请先运行: sudo ./setup_server.sh"
        exit 1
    fi
    
    # 检查MySQL
    if ! systemctl is-active --quiet mysqld && ! systemctl is-active --quiet mysql; then
        print_error "MySQL服务未运行"
        print_info "启动MySQL: sudo systemctl start mysqld"
        exit 1
    fi
    
    # 检查配置文件
    if [ ! -f "$CONFIG_FILE" ]; then
        print_error "配置文件不存在: $CONFIG_FILE"
        print_info "请先运行: sudo ./setup_database.sh"
        exit 1
    fi
    
    # 检查JAR包
    if [ ! -f "$APP_JAR" ]; then
        print_error "未找到JAR包: $APP_JAR"
        print_info "请将JAR包上传到当前目录"
        exit 1
    fi
    
    print_success "环境检查通过"
}

# 停止旧应用
stop_old_app() {
    print_info "停止旧应用..."
    
    if systemctl list-units --full -all | grep -q "$APP_NAME.service"; then
        if systemctl is-active --quiet $APP_NAME; then
            sudo systemctl stop $APP_NAME
            print_success "已停止旧应用"
        else
            print_info "应用未运行"
        fi
    else
        # 查找并杀死进程
        PID=$(ps -ef | grep "$APP_JAR" | grep -v grep | awk '{print $2}')
        if [ ! -z "$PID" ]; then
            kill -15 $PID
            sleep 2
            print_success "已停止进程: $PID"
        else
            print_info "没有运行中的应用"
        fi
    fi
}

# 备份旧版本
backup_old_version() {
    print_info "备份旧版本..."
    
    if [ -f "$APP_DIR/$APP_JAR" ]; then
        BACKUP_FILE="$APP_DIR/${APP_JAR}.backup.$(date +%Y%m%d_%H%M%S)"
        sudo cp "$APP_DIR/$APP_JAR" "$BACKUP_FILE"
        print_success "已备份到: $BACKUP_FILE"
    else
        print_info "没有旧版本需要备份"
    fi
}

# 部署新版本
deploy_new_version() {
    print_info "部署新版本..."
    
    # 创建目录
    sudo mkdir -p "$APP_DIR"
    sudo mkdir -p "$LOG_DIR"
    
    # 复制JAR包
    sudo cp "$APP_JAR" "$APP_DIR/"
    sudo chmod 755 "$APP_DIR/$APP_JAR"
    
    print_success "新版本已部署"
}

# 创建systemd服务
create_systemd_service() {
    print_info "配置systemd服务..."
    
    SERVICE_FILE="/etc/systemd/system/$APP_NAME.service"
    
    sudo tee "$SERVICE_FILE" > /dev/null <<EOF
[Unit]
Description=Kaizeli Project Management Application
After=network.target mysql.service

[Service]
Type=simple
User=root
WorkingDirectory=$APP_DIR
ExecStart=$JAVA_HOME/bin/java -Xms512m -Xmx1024m -XX:+UseG1GC -jar $APP_DIR/$APP_JAR --spring.config.location=$CONFIG_FILE
ExecStop=/bin/kill -15 \$MAINPID
Restart=on-failure
RestartSec=10
StandardOutput=append:$LOG_DIR/app.log
StandardError=append:$LOG_DIR/error.log

[Install]
WantedBy=multi-user.target
EOF
    
    sudo systemctl daemon-reload
    sudo systemctl enable $APP_NAME
    
    print_success "systemd服务已配置"
}

# 启动应用
start_application() {
    print_info "启动应用..."
    
    sudo systemctl start $APP_NAME
    sleep 5
    
    # 检查服务状态
    if sudo systemctl is-active --quiet $APP_NAME; then
        print_success "应用启动成功！"
        return 0
    else
        print_error "应用启动失败"
        print_info "查看日志: sudo journalctl -u $APP_NAME -n 50"
        return 1
    fi
}

# 检查应用健康状态
check_application_health() {
    print_info "检查应用健康状态..."
    
    # 等待应用完全启动
    for i in {1..30}; do
        if curl -sf http://localhost:8086 > /dev/null 2>&1; then
            print_success "应用响应正常"
            return 0
        fi
        sleep 2
    done
    
    print_warning "应用可能仍在启动中，请稍后检查"
    return 1
}

# 获取服务器IP
get_server_ip() {
    # 尝试获取公网IP
    PUBLIC_IP=$(curl -s ifconfig.me 2>/dev/null || echo "")
    
    if [ -z "$PUBLIC_IP" ]; then
        # 获取内网IP
        PUBLIC_IP=$(hostname -I | awk '{print $1}')
    fi
    
    echo "$PUBLIC_IP"
}

# 显示完成信息
show_completion_info() {
    SERVER_IP=$(get_server_ip)
    
    cat <<EOF

${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}
${GREEN}  🎉 部署完成！${NC}
${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}

${BLUE}🌐 访问地址：${NC}
   应用首页: ${YELLOW}http://$SERVER_IP:8086${NC}
   登录页面: ${YELLOW}http://$SERVER_IP:8086/login.html${NC}
   API文档: ${YELLOW}http://$SERVER_IP:8086/doc.html${NC}

${BLUE}📝 日志查看：${NC}
   实时日志: ${YELLOW}sudo journalctl -u $APP_NAME -f${NC}
   应用日志: ${YELLOW}tail -f $LOG_DIR/app.log${NC}
   错误日志: ${YELLOW}tail -f $LOG_DIR/error.log${NC}

${BLUE}🔧 服务管理：${NC}
   查看状态: ${YELLOW}sudo systemctl status $APP_NAME${NC}
   停止服务: ${YELLOW}sudo systemctl stop $APP_NAME${NC}
   重启服务: ${YELLOW}sudo systemctl restart $APP_NAME${NC}
   查看日志: ${YELLOW}sudo journalctl -u $APP_NAME -n 100${NC}

${BLUE}⚠️  重要提示：${NC}
   1. 确保腾讯云控制台已开放8086端口
   2. 如无法访问，请检查防火墙配置
   3. 首次登录请使用管理员账号

${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}

EOF
}

# 主函数
main() {
    show_header
    
    # 检查权限
    if [ "$EUID" -ne 0 ] && ! sudo -n true 2>/dev/null; then
        print_error "请使用root用户或具有sudo权限的用户运行此脚本"
        exit 1
    fi
    
    check_environment
    echo ""
    
    stop_old_app
    echo ""
    
    backup_old_version
    echo ""
    
    deploy_new_version
    echo ""
    
    create_systemd_service
    echo ""
    
    start_application
    echo ""
    
    check_application_health
    
    show_completion_info
}

# 运行主函数
main

